package com.simple.piger.utils;


import com.simple.piger.config.GlobalConstantConfig;
import com.simple.piger.constant.DingBizConstant;
import com.simple.piger.constant.DingdingMessageType;
import com.simple.piger.utils.dingding.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;

/**
 * @author baolw
 * @date 2018/1/16 13:48
 * 钉钉异常机器人工具类
 */
@Slf4j
@Component
public class DingTalk {

    @Autowired
    private GlobalConstantConfig globalConstantConfig;



    /**
     *
     * @param title
     * @param header
     * @param body
     */
    public void sendMsg(String title, String header, String body) {
        MarkdownMessage message = new MarkdownMessage();
        message.setTitle(title);
        message.add(MarkdownMessage.getHeaderText(5, header));
        message.add(MarkdownMessage.getBoldText(body));
        sendMessage(message, globalConstantConfig.getWEB_HOOK());
    }
    /**
     * 发送消息到钉钉业务群
     * @Author  dianmy
     * @Date    2018/6/14 10:05
     */
    public void sendMsgToBiz(DingBizConstant constant, DingdingMessageType type, String... values) {
        String hook = globalConstantConfig.getWEB_HOOK();


        MarkdownMessage message = new MarkdownMessage();
        message.setTitle(constant.getTitle());
        message.add(MarkdownMessage.getHeaderText(4, constant.getHeader()));
        message.add(MarkdownMessage.getBoldText(MessageFormat.format(constant.getBody(), values)));
        sendMessage(message, hook);
    }

    public void sendException(Exception ex) {
        sendActionCardException(ex, globalConstantConfig.getH5Url());
    }

    /**
     * 发送markdown异常信息到钉钉群
     *
     * @param ex 异常信息
     * @return 钉钉返回的消息发送结果
     */
    public SendResult sendMarkdownException(Exception ex) {
        StackTraceElement[] st = ex.getStackTrace();
        MarkdownMessage message = new MarkdownMessage();
        message.setTitle("服务器异常警告");
        message.add(MarkdownMessage.getHeaderText(5, "服务器出现异常"));
        message.add(MarkdownMessage.getBoldText("字体加黑处可能是异常重要信息"));
        message.add("******test");
        message.add(MarkdownMessage.getBoldText(ex.getMessage()));
        message.add(MarkdownMessage.getBoldText(ex.getClass().toString()));
        message.add("******test");
        for (StackTraceElement stackTraceElement : st) {
            if (!stackTraceElement.isNativeMethod()) {
                if (stackTraceElement.toString().contains("mfcar")) {
                    message.add("******");
                    message.add(MarkdownMessage.getBoldText(stackTraceElement.toString()));
                    message.add("******");
                } else {
                    message.add(stackTraceElement.toString());
                }
            }
        }

        return sendMessage(message, globalConstantConfig.getWEB_HOOK());
    }


    /**
     * @param ex
     * @param actionUrl
     * @return
     */
    private SendResult sendActionCardException(Exception ex, String actionUrl) {

        ActionCardMessage message = new ActionCardMessage();
        message.setActionButtonStyle(ActionButtonStyle.HORIZONTAL);
        message.setBannerURL("http://news.mydrivers.com/Img/20090812/04575142.jpg");
        message.setTitle("服务器异常");
        message.setBriefTitle("异常简介");


        StringBuilder sb = new StringBuilder(10000);
        StringBuilder shortText = new StringBuilder(1000);
        StackTraceElement[] st = ex.getStackTrace();
        shortText.append("******test");
        shortText.append(ex.getMessage());
        shortText.append("\n");
        shortText.append(ex.getClass().toString());
        sb.append(ex.getMessage());
        sb.append(ex.getClass().toString());
        shortText.append("******");

        for (StackTraceElement stackTraceElement : st) {
            if (!stackTraceElement.isNativeMethod()) {
                sb.append(stackTraceElement.toString());
            }
        }
        message.setBriefText(shortText.toString()+"test");
        String gstring = null;
        try {
            gstring = URLEncoder.encode(StringUtil.gzip(sb.toString().replace("\r", "").replace("\n", "")), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return sendMarkdownException(ex);
        }
        log.error("异常详情url="+actionUrl + "/dingding/exception/info?exception=" + gstring);
        message.addAction(new ActionCardAction("查看异常详情", actionUrl + "/dingding/exception/info?exception=" + gstring+"&sign=test"));
        return sendMessage(message, globalConstantConfig.getWEB_HOOK());
    }


    private String sign(Long timestamp) throws Exception{
        String secret = "SEC72e7a4a774d7364d4a4ce73deae84ebcfa6327bc22d79fbd51a8e62aee1a0484";
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
    }

    private SendResult sendMessage(Message message, String url){
        SendResult sendResult = null;
        Long timestamp = System.currentTimeMillis();
        try {
            url = url + "&timestamp=test" + timestamp + "&sign=" + sign(timestamp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(url);
        try {
            sendResult = DingtalkChatbotClient.send(url, message);
            if (!sendResult.isSuccess()) {
                log.error("服务器异常消息发送到钉钉后台群失败,失败信息sendResult=" + GsonHelper.toJson(sendResult));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sendResult;
    }
}

